/**
 * 审批页面
 * 跳转时传入 {
 *   approveType:'业务类型', 
 *   dictKey:'业务key',
 *   backPage:'返回页面'
 * }
 */
import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, Image, FlatList, TextInput
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { ApproveItemContainer } from './ApproveItemContainer';
import { Tabs } from '../_component/tabs';
import OrderApproveService from '../_common/service';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { NewAccountHome } from '../../../../components/common/newAccountHome';
import { RangTime } from '../../../../component/common/RangTime.js';
import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http'
import { Item, TabHeading } from 'native-base';
const scale = GLOBAL.SCALE;

const calendar = require('../../../../imgs/global/timeSelectIcon.png');
const searchIcon = require('../../../../imgs/global/whiteSearch.png');
const TAB_LIST = [
	{
		name: '采购',
		id: 0, // TODO
	}, {
		name: '销售',
		id: 1, // TODO
	}, {
		name: '闭口',
		id: 2, // TODO
	}
]

export class ApproveListPageNew extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { params } = navigation.state;
		return {
			headerTitle: '化销成交报告审批',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('HomePage') }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.params = this.props.navigation.state.params;
		this.state = {
			tabIndex: 0,
			companyIndex: 0,
			newLotData: [],  // 待审批
			status: 'loading',
			loadIcon: false,  // 下拉涮新的 图标
			alertShow: false,
			options: [],
			choice: {},
			refuseModalVisible: false,
			showTimeModal: false, // 时间选择弹层
			dataNum: [0, 0, 0],
			corpId: ''
		}
		this.pageNo = 1;
		this.totalPage = 1;
		this.pageParams = {
			startDate: '',
			endDate: '',
			searchContent: null,
			orderType: 'P',
		};
	}

	async componentWillMount() {
		await this._getListData();
	}


	//获取待审批,已审批列表
	async _getListData() {
		let { tabIndex } = this.state;
		if (this.pageParams.searchContent === '') {
			this.pageParams.searchContent = null
		}
		if (this.pageParams.startDate === '') {
			this.pageParams.startDate = null
		}
		if (this.pageParams.endDate === '') {
			this.pageParams.endDate = null
		}
		this.setState({
			loadIcon: true
		})

		let sendCountData = {
			startDate: this.pageParams.startDate,
			endDate: this.pageParams.endDate,
			searchContent: this.pageParams.searchContent,
		}
		let options = await HTTP.POST(API_GENERATE(API.AUDIT_MUL_COUNT), sendCountData)
		options.map(item => {
			item.rowCount = item.taskCnt
		})
		let sendData = {
			pageNo: this.pageNo,
			corpId: options[this.state.companyIndex].corpId,
			startDate: this.pageParams.startDate,
			endDate: this.pageParams.endDate,
			searchContent: this.pageParams.searchContent,
			orderType: this.pageParams.orderType,
			historyFlag: 0
		}
		let responseData = await HTTP.POST(API_GENERATE(API.ORDER_LOT), sendData)
		let orderCount = options[this.state.companyIndex]
		// let orderCount = await HTTP.POST(API_GENERATE(API.ORDER_COUNT_TYPE), sendData);
		this.setState({
			options,
			choice: options[this.state.companyIndex],
			loadIcon: false
		});

		if (responseData) {
			this.totalPage = responseData.totalPage;
			let dataNum = [orderCount.purchaceTaskCnt, orderCount.saleTaskCnt, orderCount.oppTaskCnt]
			// let dataNum = [orderCount.purchaseCount, orderCount.saleCount, orderCount.oppoCount]
			if (this.pageNo != 1) {  // 加载
				this.setState({
					newLotData: this.state.newLotData.concat(responseData.rows),
					status: 'data',
					dataNum
				})
			} else { // 刷新
				this.setState({
					newLotData: responseData.rows,
					status: responseData.rows.length ? 'data' : 'empty',
					dataNum
				})
			}
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	// 下拉更新函数
	_isLoadRefresh() {
		this.pageNo = 1;
		this._getListData();
	}

	//上啦加载
	_loadData() {
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this._getListData({
				pageNo: this.pageNo,
				onrefresh: true
			});
		}
	}

	//tab 切换
	_tabs = (index) => {
		this.pageNo = 1;
		if (index === 0) {
			this.pageParams.orderType = 'P'
		}
		else if (index === 1) {
			this.pageParams.orderType = 'S'
		}
		else {
			this.pageParams.orderType = 'OPPO'
		}
		this.setState({
			tabIndex: index,
			status: 'loading',
			alertShow: false
		}, function () {
			this._getListData();
		})
	}

	//跳审批页面
	_goDetail = (paramsData, title) => {
		this.props.navigation.navigate(paramsData.resUrl, {
			paramsData,
			title,
			status: this.state.tabIndex ? 'HASLOT' : 'LOT',
			choice: this.state.choice
		})
	}

	//数据加载出错回调
	_onErrorPress = () => {
		this.setState({
			status: 'loading'
		}, function () {
			this._getListData();
		})
	}
	//选择时间
	_resultCall = (resultData) => {
		this.pageParams.startDate = resultData.startTime || '';
		this.pageParams.endDate = resultData.endTime || '';
		this.setState({
			showTimeModal: false
		}, () => {
			this.pageNo = 1
			this._isLoadRefresh()
		})
	}

	// 一条数据
	_renderItem(list) {
		return (
			<ApproveItemContainer
				itemInfo={list.item}
				approveType={this.params.approveType}
				dictKey={this.params.dictKey}
				choice={this.state.choice}
				loadRefresh={() => {
					this.pageNo = 1
					this._isLoadRefresh();
				}}
				goDetail={(paramsData, title) => {
					this._goDetail(paramsData, title);
				}}
			/>

		)
	}

	_getSearchView() {
		/**
		 * 客户列表页隐藏头部，此处 搜索框和添加企业按钮作为头部展示
		 */
		return (
			<View style={styles.searchCell}>
				<TouchableOpacity style={styles.searchInputCell} activeOpacity={1} onPress={() => {
					const { navigate } = this.props.navigation;
					navigate('EnterpriseSearchPage', {
					});
				}}>
					<View style={styles.searchInput}>
						<Image source={searchPic} style={styles.searchPlaceholderPic} />
					</View>
				</TouchableOpacity>
				<TouchableOpacity style={styles.searchLeftCell} activeOpacity={1} onPress={() => {
					const { navigate } = this.props.navigation;
					navigate('EnterpriseCreateBaseInfo', { choice: this.state.choice });
				}}>
				</TouchableOpacity>
				<TouchableOpacity activeOpacity={1} onPress={() => {
					this.setState({
						filterModalVisible: true,
					});
				}}>
					<Text style={styles.filterText}>筛选</Text>
				</TouchableOpacity>
			</View>
		);
	}

	render() {
		let { tabIndex, companyName, newLotData, status, alertShow, choice, options, showTimeModal, dataNum } = this.state;
		// const searchView = this._getSearchView();
		let { startDate, endDate } = this.pageParams;
		return (
			<View style={styles.container}>
				<View style={styles.filterWrap}>
					<View>
						<Image source={searchIcon} style={styles.searchIcon} />
						<TextInput
							ref="enterpriseInput"
							style={styles.searchInput}
							underlineColorAndroid='transparent'
							placeholder={"请输入商品名称/订单号"}
							placeholderTextColor="#fff"
							maxLength={30}
							returnKeyType={'search'}
							defaultValue={this.pageParams.searchContent}
							onChangeText={(txt) => { this.pageParams.searchContent = txt; }}
							onSubmitEditing={() => { this._isLoadRefresh(); }}
						/>
					</View>
					<TouchableOpacity activeOpacity={.8} style={styles.dateWrap} onPress={() => {
						this.setState({
							showTimeModal: true,
						})
					}}>
						<View style={styles.dateImgWrap}>
							<Image source={calendar} style={{ width: 15 * scale, height: 17 * scale, tintColor: '#fff' }} />
						</View>
						<View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', width: 70 }}>
							<Text style={[styles.dateText, { marginBottom: 5 }]}>{startDate || '开始时间'}</Text>
							<Text style={styles.dateText}>{endDate || '结束时间'}</Text>
						</View>
					</TouchableOpacity>
				</View>
				{options.length > 1 ?
					<NewAccountHome
						fn={(val) => {
							this.setState({ companyIndex: val }, () => {
								this.pageNo = 1;
								this._getListData()
							})
						}}
						options={options}
						choice={choice} />
					: null}
				<View style={styles.tabWrap}>
					{
						TAB_LIST.map((item, index) => {
							return (
								<TouchableOpacity activeOpacity={1} onPress={() => { this._tabs(index); }} key={index} style={[styles.tabItem, this.state.tabIndex == item.id ? { backgroundColor: style.color.themeColor } : { backgroundColor: 'transparent' }]}>
									<Text style={[styles.tabText, this.state.tabIndex == item.id ? { color: '#fff' } : { color: style.color.themeColor }]}>{item.name}</Text>
									{dataNum[index] ?
										<View style={[styles.numPoint, this.state.tabIndex == item.id ? { backgroundColor: '#fff' } : { backgroundColor: 'red' }]}></View> : null
									}
									{/* <Text style={[styles.tabText, this.state.tabIndex == item.id ? { fontWeight: 'bold' } : { opacity: .8 }]}> {dataNum[index]}</Text> */}
								</TouchableOpacity>
							)
						})
					}
				</View>
				{/* <Tabs tabIndex={tabIndex} checkTab={(tab) => { this._tabs(tab); }} /> */}
				<NavigationEvents onWillFocus={async () => {
					await this._getListData()
				}} onDidBlur={() => { this.pageNo = 1; }} />
				{
					status == 'data' ? (
						<View style={styles.listBox}>
							<FlatList
								data={newLotData}
								renderItem={this._renderItem.bind(this)}
								refreshing={this.state.loadIcon}
								onRefresh={this._isLoadRefresh.bind(this)}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this._loadData() }}
							/>
						</View>
					) : null
				}
				<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this._onErrorPress} />
				{
					showTimeModal ? <RangTime isVisible={true} markedDates={null} startTime={this.pageParams.startDate} endTime={this.pageParams.endDate} closeCall={() => { this.setState({ showTimeModal: false }) }} resultCall={this._resultCall} /> : null
				}
				{/* <SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this._isLoadRefresh();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} /> */}

			</View >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white,
	},
	listItem: {
		width: '100%',
		paddingTop: 12 * scale,
		paddingBottom: 12 * scale,
		flexDirection: 'row',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
	},
	leftImg: {
		width: 40 * scale,
		height: 40 * scale,
		marginLeft: 15 * scale
	},
	conent: {
		width: 265 * scale,
		paddingLeft: 15 * scale
	},
	rightText: {
		color: '#2F7BFF'
	},
	titleBox: {
		flexDirection: 'row',
		alignItems: 'center',
		marginBottom: 5 * scale
	},
	title: {
		fontSize: 14 * scale,
		color: '#222',

	},
	infoText: {
		fontSize: 12 * scale,
		color: '#8b8b8b'
	},
	elementImg: {
		width: 21 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale
	},
	listBox: {
		flex: 1,
		// height: '100%',
		//paddingBottom: 40 * scale,
		backgroundColor: style.color.bgGray,
		paddingHorizontal: 10,
	},
	//列表item样式
	orderText: {
		fontSize: 12 * scale,
		color: '#8B8B8B'
	},
	orderVal: {
		fontSize: 12 * scale,
		color: '#000'
	},
	orderCol: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 25 * scale,
		width: 175.5 * scale,
	},
	orderMain: {
		flexDirection: 'row',
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		flexWrap: 'wrap'
	},
	orderHeadText: {
		fontSize: 14 * scale,
		color: '#222',
		marginRight: 6 * scale,
		marginLeft: 6 * scale,
		flexWrap: 'wrap',
		// width: '70%'

	},
	orderHeadLeft: {
		height: 44 * scale,
		alignItems: 'center',
		flexDirection: 'row',
	},
	orderHead: {
		width: 351 * scale,
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		height: 44 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
		flexDirection: 'row',
	},
	orderCell: {
		width: 375 * scale,
		backgroundColor: '#fff',
		alignItems: 'center',
		marginBottom: 12 * scale,
	},
	order: {
		width: 351 * scale,
	}, conImage: {
		width: 20 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale,
	}, forwardText: {
		paddingTop: 2 * scale,
		marginTop: 2 * scale,
		marginLeft: 6 * scale,
		width: 30 * scale,
		height: 16 * scale,
		backgroundColor: '#49CAFF',
		color: '#FFFFFF',
		fontSize: 11 * scale,
		textAlign: 'center',
		borderRadius: 4 * scale,
	},
	statusText: {
		fontSize: 13 * scale,
		color: style.color.themeColor,
	},
	accountSelect: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	filterWrap: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		position: 'relative',
		paddingLeft: 15,
		paddingRight: 5,
		paddingBottom: 10
	},
	dateWrap: {
		width: 110 * scale,
		height: 36 * scale,
		paddingLeft: 36 * scale,
		borderRadius: 18 * scale,
		// backgroundColor: 'rgba(255 ,255 , 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		paddingRight: 14 * scale,
	},
	dateImgWrap: {
		marginRight: 5,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	dateText: {
		fontSize: 10 * scale,
		color: '#fff',
		textAlign: 'center'
	},
	dateLine: {
		width: 7 * scale,
		height: 1 * scale,
		backgroundColor: 'rgba(255, 255, 255, .36)',
		marginTop: 3 * scale,
		marginBottom: 3 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: 250 * scale,
		textAlign: 'center',
		// paddingLeft: 30 * scale,
		// paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .4)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 18 * scale,
		height: 18 * scale,
		position: 'absolute',
		left: 15 * scale,
		top: 10 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	tabWrap: {
		backgroundColor: style.color.bgGray,
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 10,
		paddingBottom: 10
	},
	tabItem: {
		// flex:1,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 16 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		marginHorizontal: 10,
		borderWidth: 1,
		borderRadius: 20,
		borderColor: style.color.themeColor
	},
	tabText: {
		color: '#fff'
	},
	numPoint: { backgroundColor: '#fff', width: 5, height: 5, position: 'absolute', borderRadius: 16, right: 10, top: 5 }
})